// src/utils/permission.js
import { useUserStore } from '@/stores/userStore'

/**
 * 检查是否为超级管理员
 * @returns {boolean}
 */
export const isAdmin = () => {
  const userStore = useUserStore()
  return userStore.isAdmin
}

/**
 * 检查单个权限
 * @param {string} permission 权限标识
 * @returns {boolean}
 */
export const hasPermission = (permission) => {
  if (!permission) return true
  
  const userStore = useUserStore()
  
  // 超级管理员拥有所有权限
  if (userStore.isAdmin) {
    return true
  }
  
  return userStore.permissions.includes(permission)
}

/**
 * 检查多个权限（任一满足即可）
 * @param {string[]} permissions 权限标识数组
 * @returns {boolean}
 */
export const hasAnyPermission = (permissions) => {
  if (!permissions || permissions.length === 0) return true
  
  const userStore = useUserStore()
  
  // 超级管理员拥有所有权限
  if (userStore.isAdmin) {
    return true
  }
  
  return permissions.some(p => userStore.permissions.includes(p))
}

/**
 * 检查所有权限（必须全部满足）
 * @param {string[]} permissions 权限标识数组
 * @returns {boolean}
 */
export const hasAllPermissions = (permissions) => {
  if (!permissions || permissions.length === 0) return true
  
  const userStore = useUserStore()
  
  // 超级管理员拥有所有权限
  if (userStore.isAdmin) {
    return true
  }
  
  return permissions.every(p => userStore.permissions.includes(p))
}

/**
 * 权限指令 - 用于v-if等指令
 * @param {string|string[]} permissions 权限标识
 * @returns {boolean}
 */
export const checkPermission = (permissions) => {
  if (Array.isArray(permissions)) {
    return hasAnyPermission(permissions)
  }
  return hasPermission(permissions)
}

/**
 * 获取用户权限列表
 * @returns {string[]}
 */
export const getUserPermissions = () => {
  const userStore = useUserStore()
  return userStore.permissions
}

/**
 * 获取用户角色列表
 * @returns {string[]}
 */
export const getUserRoles = () => {
  const userStore = useUserStore()
  return userStore.roles
} 